import { CqkjMap } from "../Basic/CqkjMap";
import { MapElement, MapElementOption } from "../Basic/MapElement";
import { setValue } from "../Util/common";
import data from '../Asset/flyArea.json'
import bg from '../Asset/flyareaInfo.png'
import { Image } from "zrender";
import { PROJECTION, ZERO2, ZERO3 } from "../Util/static";
import { CanvasTexture, Group, Vector2 } from "three";
import { FixAxisSprite, FixAxisSpriteMaterial } from "../Basic/FixAxisSprite";


export class FlyArea extends MapElement<MapElementOption>{
  image: Image;
  root = new Group()
  get show(): boolean {
    return this.option.show
  }
  set show(val: boolean) {
    setValue(this.option, 'show', val, () => {
      this.root.visible=val
      val?this.image.show():this.image.hide()
    })
  }

  constructor(map: CqkjMap) {
    super(map, {
      name: '飞行情报区',
      show: false,
    })
    const { root } = this
    root.visible=this.option.show
    const east = PROJECTION.lonToX(135.08851148)
    const west = PROJECTION.lonToX(73.5011421)
    const south = PROJECTION.latToY(14.5)
    const north = PROJECTION.latToY(53.56090105)

    const image = new Image({
      scaleY: -1,
      x: west,
      y: north,
      style: {
        image: bg,
        opacity: 0.1,
        width: east - west,
        height: north - south,
      }
    })
    image.hide()
    map.ground.root.add(image)
    this.image = image

    data.features.forEach(e => {
      const [lon, lat] = e.geometry.coordinates
      const x = PROJECTION.lonToX(lon)
      const y = PROJECTION.latToY(lat)

      const label = createLabel(e.properties.name)
      label.position.set(x, y, 0)
      label.renderOrder = 5
      root.add(label)
    })

    map.scene.add(root)
  }

  onDestroy(): void {
    throw new Error("Method not implemented.");
  }

}

const CENTER = new Vector2(0.5, 0.5)

function createLabel(name: string) {
  const width = name.length * 12 + 2;
  const height = 16;
  const canvas = document.createElement("canvas");
  canvas.width = width;
  canvas.height = height;
  const ctx = canvas.getContext("2d")!;
  ctx.font = "12px OPPOSans";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillStyle = "#2EDD94";
  ctx.fillText(name, width / 2, height / 2);
  const texture = new CanvasTexture(canvas);
  return new FixAxisSprite(new FixAxisSpriteMaterial({
    size: ZERO2,
    center: CENTER,
    scale: new Vector2(0.001 * width, 0.001 * height),
    direction: ZERO3,
    axis: "",
    uniforms: {
      u_texture: {
        value: texture,
      },
    },
    fragmentShader: /* glsl */ `
    varying vec2 v_uv;
    uniform sampler2D u_texture;
    void main() {
      gl_FragColor = texture2D(u_texture,v_uv);
    }
    `,
  }))
}